/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package sundeepk.github.com.sample;

import ohos.aafwk.ability.Ability;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

/**
 * MenuDialog
 */
public class MenuDialog extends PopupDialog {
    private ComponentContainer mComponent;
    private final Context mContext;
    private Ability mAbility;
    private int dialogWidth;

    /**
     * getOwnerAbility
     *
     * @return Ability
     */
    public Ability getOwnerAbility() {
        return mAbility;
    }

    public MenuDialog(Context context, Component contentComponent, int menuId) {
        super(context, contentComponent);
        mContext = context;
        if (context instanceof Ability) {
            mAbility = (Ability) context;
        }
    }

    public MenuDialog(Context context, Component contentComponent, int width, int height, int menuId) {
        super(context, contentComponent, width, height);
        mContext = context;
        this.dialogWidth = width;
        if (context instanceof Ability) {
            mAbility = (Ability) context;
        }
        if (menuId != 0) {
            mComponent = (ComponentContainer) LayoutScatter.getInstance(mContext).parse(menuId, null, false);
        }
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        if (mComponent != null) {
            setHasArrow(false);
            setAutoClosable(true);
            setCustomComponent(mComponent);
            int screenWidth = DisplayManager.getInstance().getDefaultDisplay(mContext).get().getAttributes().width;
            setOffset(screenWidth - 30 - dialogWidth, 160);
        }
    }

    /**
     * initListener
     *
     * @param listener listener
     */
    public void initListener(Component.ClickedListener listener) {
        if (mComponent == null) {
            return;
        }
        for (int i = 0; i < mComponent.getChildCount(); i++) {
            mComponent.getComponentAt(i).setClickedListener(listener);
        }
    }

}